import React, {Component, cloneElement, Children} from 'react'
import {findDOMNode} from 'react-dom'
import F from 'lodash/fp'

class Uploader extends Component {
    constructor(props) {
        super(props)
        let {onQueued, onProgress, onError, onSuccess, options} = this.props

        this.uploader = WebUploader.create(options)
            .on('fileQueued', onQueued)
            .on('uploadProgress', (file, percentage) => {
                this.setState({percentage})
                onProgress(file, percentage)
            })
            .on('uploadError', onError)
            .on('uploadSuccess', onSuccess)
        window.uploader = this.uploader
        this.state = {percentage: 0}
    }
    componentDidMount() {
    }

    render() {
        let {children} = this.props
        return (
            <div>
                {
                    Children.map(this.props.children, t => {
                        if (t.props.uploaderPick) {
                            return cloneElement(t, {
                                ready: dom => {
                                    dom 
                                    && dom.querySelector('.webuploader-pick') 
                                    || this.uploader.addButton({id:dom, multiple: false})
                                },
                            })
                        } else if (t.props.uploaderProgress) {
                            return cloneElement(t, {percentage: this.state.percentage})
                        }
                        return t
                    })
                }
            </div>
        )
    }
}

Uploader.defaultProps = {
    onProgress: () => null,
    onError: () => null,
    onSuccess: () => null,
    onQueued: () => null,
    options: {
        pick: {multiple: false},
        server: SONG_UPLOAD_URL,
        resize: false,
        auto: true,
        accept: {
            title: 'Images',
            extensions: 'mp3',
            mimeTypes: 'audio/mpeg'
        }
    }
}

export default Uploader